<template>
  <s-clean-layout :title="isAdd ? '添加来往' : '编辑来往'" navbar="normal">
    <view class="edit-container">
      <!-- 移除顶部导航栏，使用s-clean-layout的标题 -->
      
      <!-- 表单内容 -->
      <view class="form-container">
        <!-- 日期选择 -->
        <view class="form-item" @tap="openDatePicker">
          <view class="item-icon">
            <uni-icons type="calendar" size="22" color="#f8b62d"></uni-icons>
          </view>
          <view class="item-label">日期</view>
          <view class="item-content">{{ formData.date }}</view>
          <view class="item-arrow">
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view>
        </view>
        
        <!-- 姓名输入 -->
        <view class="form-item">
          <view class="item-icon">
            <uni-icons type="person" size="22" color="#f87d6d"></uni-icons>
          </view>
          <view class="item-label">姓名</view>
          <input 
            class="item-input" 
            type="text" 
            v-model="formData.contactName" 
            placeholder="输入姓名"
            placeholder-class="input-placeholder"
          />
          <view class="item-note" v-if="formData.contactName">
            <!-- <text>(重名备注)</text> -->
          </view>
          <view class="item-clear" v-if="formData.contactName" @tap="formData.contactName = ''">
            <uni-icons type="clear" size="16" color="#f87d6d"></uni-icons>
          </view>
        </view>
        
        <!-- 礼金输入 -->
        <view class="form-item">
          <view class="item-icon">
            <uni-icons type="gift" size="22" color="#f8b62d"></uni-icons>
          </view>
          <view class="item-label">礼金</view>
          <input 
            class="item-input" 
            type="digit" 
            v-model="formData.amount" 
            placeholder="输入金额"
            placeholder-class="input-placeholder"
          />
        </view>
        
        <!-- 关系区域 -->
        <view class="form-item" v-if="sections.relation.show" @tap="goToRelationSelect">
          <view class="item-icon">
            <uni-icons type="person" size="22" color="#f87d6d"></uni-icons>
          </view>
          <view class="item-label">关系</view>
          <view class="item-content">{{ formData.relation || '选择关系' }}</view>
          <view class="item-arrow">
            <uni-icons type="right" size="16" color="#ccc"></uni-icons>
          </view>
          <view class="item-clear" @tap.stop="toggleSection('relation')">
            <uni-icons type="close" size="16" color="#ccc"></uni-icons>
          </view>
        </view>
        
        <!-- 备注区域 -->
        <view class="form-item" v-if="sections.note.show">
          <view class="item-icon">
            <uni-icons type="compose" size="22" color="#f87d6d"></uni-icons>
          </view>
          <view class="item-label">备注</view>
          <input 
            class="item-input" 
            type="text" 
            v-model="formData.note" 
            placeholder="备注(选填)"
            placeholder-class="input-placeholder"
          />
          <view class="item-clear" @tap="toggleSection('note')">
            <uni-icons type="close" size="16" color="#ccc"></uni-icons>
          </view>
        </view>
        
        <!-- 礼品区域 -->
        <view class="form-item" v-if="sections.gift.show">
          <view class="item-icon">
            <uni-icons type="gift" size="22" color="#f87d6d"></uni-icons>
          </view>
          <view class="item-label">礼品</view>
          <input 
            class="item-input" 
            type="text" 
            v-model="formData.giftName" 
            placeholder="礼品名称"
            placeholder-class="input-placeholder"
          />
          <view class="item-clear" @tap="toggleSection('gift')">
            <uni-icons type="close" size="16" color="#ccc"></uni-icons>
          </view>
        </view>
        
        <!-- 图片区域 -->
        <view class="form-item" v-if="sections.photo.show">
          <view class="item-icon">
            <uni-icons type="image" size="22" color="#f87d6d"></uni-icons>
          </view>
          <view class="item-label">图片</view>
          <view class="item-content"></view>
          <view class="item-clear" @tap="toggleSection('photo')">
            <uni-icons type="close" size="16" color="#ccc"></uni-icons>
          </view>
        </view>
        
        <view class="photo-upload-container" v-if="sections.photo.show">
          <view class="photo-upload">
            <view class="photo-item" v-for="(photo, index) in formData.photos" :key="index">
              <image :src="photo" mode="aspectFill" class="photo-image" />
              <view class="photo-delete" @tap="deletePhoto(index)">
                <uni-icons type="close" size="16" color="#fff"></uni-icons>
              </view>
            </view>
            <view class="upload-btn" @tap="chooseImage">
              <text class="upload-icon">+</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 底部操作栏 -->
      <view class="bottom-actions">
        <view class="action-tag" @tap="toggleSection('relation')">
          <text>关系</text>
        </view>
        <view class="action-tag" @tap="toggleSection('note')">
          <text>备注</text>
        </view>
        <view class="action-tag" @tap="toggleSection('gift')">
          <text>礼品</text>
        </view>
        <view class="action-tag" @tap="toggleSection('photo')">
          <text>图片</text>
        </view>
      </view>
      
      <!-- 添加底部占位空间，防止内容被固定底栏遮挡 -->
      <view class="bottom-placeholder"></view>
      
      <!-- 修改底部固定操作栏，添加删除按钮 -->
      <view class="fixed-bottom">
        <!-- 添加删除按钮，仅在编辑模式显示 -->
        <view class="delete-button" v-if="!isAdd" @tap="deleteRecord">
          <uni-icons type="trash" size="20" color="#fff"></uni-icons>
          <text>删除</text>
        </view>
        <!-- 占位元素，在添加模式下保持布局一致 -->
        <view class="placeholder" v-else></view>
        <!-- 保存按钮 -->
        <view class="save-button" @tap="saveRecord">保存</view>
      </view>
      
      <!-- 日期选择器弹窗 -->
      <s-datetime-picker
        v-model:visible="showDatePicker"
        :initial-date="formData.date"
        mode="date"
        title="选择日期"
        @confirm="onDateConfirm"
      />
    </view>
  </s-clean-layout>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import GiftApi from '@/pages/money/api/gift';
import FileApi from '@/sheep/api/infra/file'; // 添加FileApi导入

// 页面状态
const isAdd = ref(true);
const giftBookId = ref(0);
const giftBookType = ref('receive');
const giftBookTitle = ref('');

// 表单数据
const formData = ref({
  date: formatDate(new Date()),
  contactName: '',
  amount: '',
  note: '',
  relation: '',
  giftName: '',
  giftAmount: '',
  gifts: [],
  photos: [],
  // 添加API所需的ID字段
  id: null,
  contactId: null,
  relationshipId: null
});

// 弹窗控制
const showDatePicker = ref(false);

// 附加区域控制
const sections = ref({
  gift: { show: false },
  relation: { show: false },
  note: { show: false },
  photo: { show: false }
});

// 切换区域显示
const toggleSection = (section) => {
  sections.value[section].show = !sections.value[section].show;
};

// 选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 1,
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0];
      // 使用FileApi上传文件
      const result = await FileApi.uploadFile(tempFilePath);
      if (result && result.data) {
        // 上传成功，将文件URL添加到photos数组
        formData.value.photos.push(result.data);
        uni.showToast({
          title: '上传成功',
          icon: 'success'
        });
      }
    }
  });
};

// 页面加载时获取路由参数
onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const params = currentPage.options || {};
  
  // 设置页面数据
  if (params.bookId) {
    giftBookId.value = Number(params.bookId);
    giftBookType.value = params.bookType || 'receive';
    giftBookTitle.value = params.title || '';
    isAdd.value = params.isAdd !== 'false';
    
    // 如果是编辑模式，获取记录详情
    if (!isAdd.value && params.id) {
      fetchRecordDetail(params.id);
    }
  } else {
    console.error('未获取到礼簿ID参数');
    uni.showToast({
      title: '参数错误',
      icon: 'none'
    });
  }
});

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 保存记录
const saveRecord = async () => {
  if (!formData.value.contactName) {
    uni.showToast({
      title: '请输入姓名',
      icon: 'none'
    });
    return;
  }
  
  if (!formData.value.amount) {
    uni.showToast({
      title: '请输入金额',
      icon: 'none'
    });
    return;
  }
  
  try {
    // 构建API请求参数
    const params = {
      id: formData.value.id, // 编辑时有值，新增时为null
      accountBookId: giftBookId.value, // 使用从路由参数获取的礼簿ID
      giftDate: formData.value.date,
      contactName: formData.value.contactName,
      contactId: formData.value.contactId,
      relationshipId: formData.value.relationshipId,
      giftAmount: parseFloat(formData.value.amount),
      giftItem: formData.value.giftName || '',
      remark: formData.value.note || '',
      fileUrls: formData.value.photos.join(',') // 添加文件URL字段，将数组转换为逗号分隔的字符串
    };
    
    console.log('保存礼金记录参数:', params);
    
    // 调用API保存记录
    const response = await GiftApi.addOrUpdateAccountBookGift(params);
    
    if (response.code === 0) {
      uni.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 500,
        success: () => {
          setTimeout(() => {
            // 修改跳转逻辑，添加刷新标记
            uni.redirectTo({
              url: `/pages/money/gift-book-detail?id=${giftBookId.value}&type=${giftBookType.value}&title=${encodeURIComponent(giftBookTitle.value)}&needRefresh=true`
            });
          }, 500);
        }
      });
    } else {
      uni.showToast({
        title: response.msg || '保存失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('保存礼金记录失败:', error);
    uni.showToast({
      title: '保存失败，请重试',
      icon: 'none'
    });
  }
};

// 格式化日期
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

// 添加时间戳转日期函数
function timestampToDate(timestamp) {
  if (!timestamp) return formatDate(new Date());
  const date = new Date(timestamp);
  return formatDate(date);
}

// 获取记录详情
const fetchRecordDetail = async (id) => {
  try {
    // 调用API获取记录详情
    const response = await GiftApi.queryAccountBookGiftDetail({
      id: id,
      accountBookId: giftBookId.value
    });
    
    if (response.code === 0 && response.data) {
      const detail = response.data;
      
      // 填充表单数据
      formData.value = {
        id: detail.id,
        date: timestampToDate(detail.giftDate), // 使用时间戳转换函数
        contactName: detail.contactName || '',
        amount: detail.giftAmount?.toString() || '',
        note: detail.remark || '',
        relation: detail.relationshipName || '',
        giftName: detail.giftItem || '',
        photos: detail.fileUrls ? detail.fileUrls.split(',') : [], // 将fileUrls字符串转换为数组
        // 保存ID字段用于提交
        contactId: detail.contactId,
        relationshipId: detail.relationshipId
      };
      
      // 显示已有的附加区域
      if (detail.relationshipName) sections.value.relation.show = true;
      if (detail.remark) sections.value.note.show = true;
      if (detail.giftItem) sections.value.gift.show = true;
      if (detail.fileUrls) sections.value.photo.show = true; // 修改判断条件为fileUrls
      
    } else {
      uni.showToast({
        title: response.msg || '获取记录详情失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取记录详情失败:', error);
    uni.showToast({
      title: '获取记录详情失败',
      icon: 'none'
    });
  }
};

// 添加删除记录方法
const deleteRecord = async () => {
  if (!formData.value.id) {
    uni.showToast({
      title: '无效的记录ID',
      icon: 'none'
    });
    return;
  }
  
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这条记录吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const response = await GiftApi.deleteAccountBookGift({
            id: formData.value.id,
            accountBookId: giftBookId.value
          });
          
          if (response.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success',
              duration: 500,
              success: () => {
                setTimeout(() => {
                  uni.navigateBack();
                }, 500);
              }
            });
          } else {
            uni.showToast({
              title: response.msg || '删除失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('删除记录失败:', error);
          uni.showToast({
            title: '删除失败，请重试',
            icon: 'none'
          });
        }
      }
    }
  });
};

// 选择日期
const onDateConfirm = (result) => {
  console.log('日期选择结果:', result);
  if (result && result.date) {
    formData.value.date = result.date;
  }
};

// 打开日期选择器
const openDatePicker = () => {
  console.log('打开日期选择器');
  showDatePicker.value = true;
};

// 删除照片
const deletePhoto = (index) => {
  formData.value.photos.splice(index, 1);
};

// 跳转到关系选择页面
const goToRelationSelect = () => {
  uni.navigateTo({
    url: '/pages/money/relation-select',
    events: {
      // 监听选择结果
      selectRelation: function(data) {
        formData.value.relation = data.relation;
        formData.value.relationshipId = data.relationshipId; // 保存关系ID
      }
    }
  });
};
</script>

<style lang="scss" scoped>
.edit-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.nav-bar {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  height: 88rpx;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-title {
  flex: 1;
  font-size: 32rpx;
  color: #333;
  text-align: center;
}

.delete-btn {
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.save-btn {
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
}

.form-container {
  margin-top: 20rpx;
  background-color: #fff;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1px solid #f5f5f5;
}

.item-icon {
  width: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
}

.item-label {
  width: 80rpx;
  font-size: 28rpx;
  color: #333;
}

.item-input {
  flex: 1;
  height: 60rpx;
  font-size: 28rpx;
  color: #333;
}

.input-placeholder {
  color: #ccc;
}

.item-content {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.item-note {
  font-size: 24rpx;
  color: #999;
  margin-right: 20rpx;
}

.item-clear {
  width: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.item-arrow {
  width: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.bottom-actions {
  display: flex;
  flex-wrap: wrap;
  padding: 20rpx 30rpx;
  background-color: #fff;
  margin-top: 20rpx;
}

.action-tag {
  height: 60rpx;
  padding: 0 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx; /* 减小字体大小 */
  color: #666;
  background-color: #f5f5f5;
  border-radius: 30rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
}

.additional-sections {
  margin-top: 20rpx;
  padding-bottom: 120rpx; /* 为底部固定栏留出空间 */
}

.section-item {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 20rpx 30rpx;
}

.section-header {
  display: flex;
  align-items: center;
  padding-bottom: 20rpx;
}

.section-icon {
  margin-right: 20rpx;
}

.section-title {
  width: 80rpx;
  font-size: 28rpx;
  color: #333;
}

.section-value {
  flex: 1;
  font-size: 28rpx;
  color: #999;
}

.section-close {
  width: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.event-tags {
  display: flex;
  flex-wrap: wrap;
  padding: 10rpx 0;
}

.event-tag {
  height: 60rpx;
  padding: 0 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  color: #666;
  background-color: #f5f5f5;
  border-radius: 30rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
}

.event-tag-active {
  background-color: #ff6b6b;
  color: #fff;
}

.photo-upload-container {
  background-color: #fff;
  padding: 0 30rpx 20rpx 150rpx;
  margin-top: -20rpx;
}

.photo-upload {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.photo-item {
  width: 160rpx;
  height: 160rpx;
  position: relative;
  flex-shrink: 0;
}

.photo-image {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}

.photo-delete {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-btn {
  width: 160rpx;
  height: 160rpx;
  border: 1px dashed #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8rpx;
  flex-shrink: 0;
}

.upload-icon {
  font-size: 60rpx;
  color: #ccc;
}

.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  background-color: #fff;
  border-top: 1px solid #eee;
  padding: 20rpx;
  z-index: 100;
}

/* 删除按钮样式 */
.delete-button {
  flex: 1;
  height: 80rpx;
  background-color: #ff4d4f;
  color: #fff;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  margin-right: 20rpx;
}

.delete-button uni-icons {
  margin-right: 10rpx;
}

/* 占位元素样式 */
.placeholder {
  flex: 1;
  margin-right: 20rpx;
}

/* 保存按钮样式 */
.save-button {
  flex: 2;
  height: 80rpx;
  background-color: #ff6b6b;
  color: #fff;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: bold;
}

/* 移除旧的保存按钮样式 */
.save-button-full {
  display: none;
}

.save-button {
  width: 240rpx;
  height: 80rpx;
  background-color: #ff6b6b;
  color: #fff;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
}

.section-content {
  padding: 10rpx 0;
}

.section-input {
  width: 100%;
  height: 60rpx;
  font-size: 28rpx;
  color: #333;
}

.section-textarea {
  width: 100%;
  height: 120rpx;
  font-size: 28rpx;
  color: #333;
}

.event-tags-container {
  background-color: #fff;
  padding: 0 30rpx 20rpx 150rpx;
  margin-top: -20rpx;
}

.event-tags {
  display: flex;
  flex-wrap: wrap;
}

.event-tag {
  height: 60rpx;
  padding: 0 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  color: #666;
  background-color: #f5f5f5;
  border-radius: 30rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
}

.event-tag-active {
  background-color: #ff6b6b;
  color: #fff;
}

.photo-upload-container {
  background-color: #fff;
  padding: 0 30rpx 20rpx 150rpx;
  margin-top: -20rpx;
}

.photo-upload {
  display: flex;
  flex-wrap: wrap;
}

.upload-btn {
  width: 160rpx;
  height: 160rpx;
  border: 1px dashed #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8rpx;
  margin-right: 20rpx;
  margin-bottom: 20rpx;
}

.upload-icon {
  font-size: 60rpx;
  color: #ccc;
}

// 添加底部占位空间样式
.bottom-placeholder {
  height: 140rpx; // 与固定底栏高度保持一致或略大
}

</style>